package org.chen.mybatis.factory;

import org.chen.mybatis.annotation.Mapper;
import org.chen.mybatis.annotation.Select;
import org.chen.spring.ChenApplicationContext;
import org.chen.spring.core.factory.BeanFactory;
import org.chen.spring.core.factory.ScanBean;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Mapper扫描类
 *
 * @author Chen
 * @since 2023/6/9 10:59
 */
public class MapperScanBean extends ScanBean {

    private final boolean hasMapperScan;

    private final MapperProxyFactory mapperProxyFactory = ChenApplicationContext.getBeanFactory().getBean(MapperProxyFactory.class);

    public MapperScanBean(List<String> componentScan, boolean hasMapperScan) {
        super(componentScan);
        this.hasMapperScan = hasMapperScan;
    }

    @Override
    protected void assembleBeanDefinition(Class<?> bean, Annotation annotation) {
        //如果有mapperScan，直接解析所有接口为Mapper
        if (hasMapperScan) {
            if (bean.isInterface()) {
                boolean isMapper = false;
                //判断是否有Select注解
                for (Method method : bean.getMethods()) {
                    if (method.isAnnotationPresent(Select.class)) {
                        isMapper = true;
                        break;
                    }
                }
                //如果有Select注解，注册为Mapper
                if (isMapper) {
                    //获取Mapper的value作为BeanName
                    String name = ((Mapper) annotation).value();
                    //获取Mapper的代理对象
                    Object mapper = mapperProxyFactory.getMapper(bean);
                    //注册到BeanFactory
                    BeanFactory.registerBean("".equals(name) ? bean.getSimpleName() : name, mapper);
                }
            }
            return;
        }
        Class<? extends Annotation> annotationType = annotation.annotationType();
        if (annotationType == Mapper.class) {
            //获取Mapper的value作为BeanName
            String name = ((Mapper) annotation).value();
            //获取Mapper的代理对象
            Object mapper = mapperProxyFactory.getMapper(bean);
            //注册到BeanFactory
            BeanFactory.registerBean("".equals(name) ? bean.getSimpleName() : name, mapper);
        }
    }
}
